package com.zr.shortlink.admin.common.biz.uesr;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.io.IOException;

/**
 * 用户信息传输过滤器
 *
 * @公众号：马丁玩编程
 */
@RequiredArgsConstructor
public class UserTransmitFilter implements Filter {

    private final StringRedisTemplate redisTemplate;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String requestURI = httpServletRequest.getRequestURI();

        // ====== 白名单路径 ======
        if ("/api/short-link/v1/user/login".equals(requestURI)) {
            // 放行登录接口，直接跳过后续逻辑
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 非白名单，执行用户上下文逻辑
        String username = httpServletRequest.getHeader("username");
        String token = httpServletRequest.getHeader("token");

        Object userInfoStr = redisTemplate.opsForHash().get("login_" + username, token);
        if (userInfoStr != null) {
            JSONObject outer = JSON.parseObject(userInfoStr.toString());
            String innerJson = outer.getString("token");

            UserInfoDTO userInfoDTO = JSON.parseObject(innerJson, UserInfoDTO.class);
            UserContext.setUser(userInfoDTO);
        }

        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            UserContext.removeUser();
        }
    }
}
